import React, { useEffect, useImperativeHandle, useState } from 'react';

import { Col, Form, Radio, Row, Select, Typography } from 'antd';
import { hasIn, size } from 'lodash';
// import FileCompleteProgress from '@/pages/EntryManage/components/FileCompleteProgress';
import { useDeepCompareEffect } from 'react-use';

import { defaultFormatResult, useRequest } from '@/hooks';
import SoftTable from '@/pages/EntryManage/components/SoftTable';
import { getEntryDevice, getSoft, preloadedSoft } from '@/pages/EntryManage/services';
import { MATERIAL } from '@/pages/EntryManage/utils';
import { transformFileList } from '@/pages/Recruitment/utils';

import UploadAvatar from '../UploadAvatar';
import WelcomeMessage from '../WelcomeMessage';
import styles from './index.less';

const { Title } = Typography;
const { Option } = Select;

const formlayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
        md: { span: 5 },
        xl: { span: 3 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
        md: { span: 18 },
        xl: { span: 16 }
    }
};

// 信息确认
const StepUserInfo = React.forwardRef(({ form, entryPersonnelData }, ref) => {
    const { getFieldDecorator } = form;
    const { entryPersonnelCode, employeeName, idPhoto, dutyName, contractOrganizationName } = entryPersonnelData;

    const [softTableData, setSoftTableData] = useState([]);
    const [softSelectData, setSoftSelectData] = useState([]);

    const [customSoftData, setCustomSoftData] = useState([]);
    useImperativeHandle(ref, () => ({
        form
    }));

    // 获取通用软件和专业软件数据源
    const { data: softList, loading: softLoading } = useRequest(() => getSoft({ entryPersonnelCode }), {
        ...defaultFormatResult
    });

    // 获取预装软件数据源
    const { data: preloadedSoftData, loading: preloadedSoftLoading } = useRequest(
        () =>
            preloadedSoft({
                entryPersonnelCode,
                choiceType: 0
            }),
        {
            ...defaultFormatResult
        }
    );

    // 获取预装软件数据源
    const { data: entryDeviceData } = useRequest(
        () =>
            getEntryDevice({
                entryPersonnelCode,
                choiceType: 0
            }),
        {
            ...defaultFormatResult
        }
    );

    useDeepCompareEffect(() => {
        const { computerType = 0, needDisplay = 1, needMouse = 1, systemType = 0 } =
            size(entryDeviceData) > 0 ? entryDeviceData[0] : {};
        const { professionalList = [], moreSoftwareList } = size(preloadedSoftData) > 0 ? preloadedSoftData[0] : {};

        // 表单回填
        form.setFieldsValue({
            computerType,
            needDisplay,
            needMouse,
            systemType,
            softwareList: professionalList,
            moreSoftwareList,
            idPhoto: transformFileList((size(idPhoto) > 0 && idPhoto[0]?.urlList) || [])
        });
    }, [entryDeviceData, preloadedSoftData, form, idPhoto]);

    useEffect(() => {
        if (size(softList) > 0) {
            // 将数据源进行分类
            setSoftTableData(softList.filter(item => item.softClass === 0));
            setSoftSelectData(softList.filter(item => item.softClass === 1));
            setCustomSoftData(softList.filter(item => item.softClass === 2));
        }
    }, [softList]);

    return (
        <div>
            <WelcomeMessage username={employeeName} />
            <Form {...formlayout}>
                <div className={styles.panelWrapper}>
                    <Title className={styles.panelTitle} level={4}>
                        入职信息
                    </Title>
                    <Form.Item className={styles.formItem} label="入职公司">
                        {contractOrganizationName || '-'}
                    </Form.Item>
                    <Form.Item className={styles.formItem} label="入职岗位">
                        {dutyName || '-'}
                    </Form.Item>
                </div>
                <div className={styles.panelWrapper}>
                    <Title className={styles.panelTitle} level={4}>
                        个人档案
                    </Title>
                    <Form.Item className={styles.formItem} label="档案信息">
                        <Row type="flex" style={{ lineHeight: '40px' }}>
                            <Col>
                                <a
                                    href={`/user/entryguidefile?entryPersonnelCode=${entryPersonnelCode}`}
                                    target="_blank"
                                    style={{ color: '#5590F6' }}
                                    rel="noopener noreferrer"
                                >
                                    核对档案
                                </a>
                            </Col>
                        </Row>
                    </Form.Item>
                    {/* <Form.Item className={styles.formItem} label="档案完整度">
                        <Row type="flex" style={{ lineHeight: '40px' }}>
                            <Col style={{ alignItems: 'center', marginRight: 12, width: 240 }}>
                                <FileCompleteProgress entryPersonnelCode={entryPersonnelCode} label />
                            </Col>
                        </Row>
                    </Form.Item> */}
                    <Form.Item className={styles.formItem} label="证件照">
                        <Row type="flex" align="top">
                            <Col span={24}>
                                {getFieldDecorator('idPhoto', {
                                    rules: [
                                        {
                                            required: true,
                                            validator(rule, value = [], callback) {
                                                const result = Array.isArray(value)
                                                    ? value
                                                    : value?.allFileList || value?.urlList || [];
                                                let isAllFileUploaded = true;
                                                if (hasIn(result[0], 'status')) {
                                                    isAllFileUploaded =
                                                        result.filter(f => f.status !== 'done').length === 0;
                                                }
                                                if (result.length && isAllFileUploaded) {
                                                    callback();
                                                } else {
                                                    callback('请上传证件照');
                                                }
                                            }
                                        }
                                    ]
                                })(<UploadAvatar categoryCode={MATERIAL.ID_PHOTO} />)}
                            </Col>
                            <Col
                                span={24}
                                style={{
                                    lineHeight: '26px',
                                    color: 'rgba(0, 0, 0, 0.45)',
                                    flex: 1
                                }}
                            >
                                <div className={styles.uploadMessage}>
                                    <div>
                                        请上传您的2寸白底、近半年内的个人证件照。 <br />
                                        该证件照将作为您的默认头像显示于所有内部系统。
                                        <br />
                                        照片要求：正面免冠，头发不遮挡眉毛、眼睛和脸颊，露出耳朵。
                                    </div>
                                    <div className={styles.uploadRules}>支持.png .jpg .jpeg格式</div>
                                </div>
                            </Col>
                        </Row>
                    </Form.Item>
                </div>
                <div className={styles.panelWrapper}>
                    <Title className={styles.panelTitle} level={4}>
                        电脑偏好
                    </Title>
                    <div
                        style={{
                            fontSize: 16,
                            color: 'rgba(0,0,0,0.45)',
                            margin: '20px 0 5px 5px'
                        }}
                    >
                        请选择您的电脑偏好，IT部门会根据您的偏好，尽量为您挑选合适的电脑：
                    </div>
                    <Form.Item className={styles.formItem} labelAlign="left" label="电脑类型">
                        {getFieldDecorator('computerType')(
                            <Radio.Group>
                                <Radio value={0}>笔记本电脑</Radio>
                                <Radio value={1}>台式整机</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem} labelAlign="left" label="系统类型">
                        {getFieldDecorator('systemType')(
                            <Radio.Group>
                                <Radio value={0}>Windows </Radio>
                                <Radio value={1}>Mac os </Radio>
                                <Radio value={2}>Linux </Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem} labelAlign="left" label="需要显示器">
                        {getFieldDecorator('needDisplay')(
                            <Radio.Group>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem} labelAlign="left" label="需要鼠标">
                        {getFieldDecorator('needMouse')(
                            <Radio.Group>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                </div>
                <div className={styles.panelWrapper}>
                    <Title className={styles.panelTitle} level={4}>
                        预装软件
                    </Title>
                    <Form.Item
                        className={styles.formItem}
                        labelAlign="left"
                        label="通用软件"
                        help={
                            <div style={{ color: 'rgba(0,0,0,0.65)', marginTop: 5 }}>
                                IT人员将统一安装通用的办公软件到您的电脑中，便于你快速上手。
                            </div>
                        }
                        style={{ marginBottom: 16 }}
                    >
                        <SoftTable data={softTableData} loading={softLoading} />
                    </Form.Item>
                    <Form.Item
                        className={styles.formItem}
                        style={{ marginBottom: 8 }}
                        labelAlign="left"
                        label="专业软件"
                    >
                        {getFieldDecorator('softwareList')(
                            <Select
                                mode="multiple"
                                placeholder="请选择"
                                loading={softLoading || preloadedSoftLoading}
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {softSelectData.map(item => (
                                    <Option key={item.id} value={item.softName}>
                                        {item.softName}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem} labelAlign="left" label="更多软件">
                        {getFieldDecorator('moreSoftwareList')(
                            <Select mode="tags" placeholder="请输入">
                                {customSoftData &&
                                    customSoftData.map(item => (
                                        <Option value={item.softName} key={item.softCode}>
                                            {item.softName}
                                        </Option>
                                    ))}
                            </Select>
                        )}
                    </Form.Item>
                </div>
            </Form>
        </div>
    );
});

export default Form.create()(StepUserInfo);
